import ListEmptyLoadingComponent from '@/components/ListEmptyLoadingComponent';
import { useMMKVBoolean } from '@/hooks/useMMkv';
import { deviceApi, DeviceCategoryModel } from '@/services/api/deviceApi';
import { StationDTO } from '@/services/api/stationApi';
import StringUtils from '@/utils/StringUtils';
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { FlashList } from '@shopify/flash-list';
import React, { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Dimensions,
  FlatList,
  TouchableOpacity,
  useWindowDimensions,
  View,
} from 'react-native';
import FastImage from 'react-native-fast-image';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Button, Text, useAppTheme } from 'tsun-smart-ui';
import NativeToast from '~/specs/NativeToast';

const windowSize = Dimensions.get('window');

const SelectDeviceCategory: React.FC = () => {
  const appTheme = useAppTheme();
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const route = useRoute<RouteProp<any>>();
  const [globalMode = true] = useMMKVBoolean('globalMode');
  const [categories, setCategories] = useState<DeviceCategoryModel[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [selectedCategory, setSelectedCategory] =
    useState<DeviceCategoryModel>();
  const { t } = useTranslation();

  useEffect(() => {
    reloadCategories();
  }, []);

  const reloadCategories = useCallback(() => {
    setLoading(true);
    deviceApi
      .getDeviceCategories()
      .then((res) => {
        setCategories(res.data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  const renderItem = useCallback(
    ({ item, index }: { item: DeviceCategoryModel; index: number }) => {
      let childrenLength = item.children?.length ?? 0;
      if (childrenLength <= 0) return null;
      let shouldAddExtra = childrenLength % 2 === 1;
      const itemWidth = Math.floor((windowSize.width - 32) / 2);
      return (
        <View>
          <Text
            className="mx-4 mb-2 mt-4"
            style={{ color: appTheme.colors?.neutral?.secondaryTitle }}
          >
            {item.name}
          </Text>
          <View className="flex-wrap gap-3 flex-row mx-3 justify-center">
            {item.children?.map((child) => {
              return (
                <DeviceItem
                  key={child.id}
                  item={child}
                  selectedCategory={selectedCategory}
                  onPress={() => setSelectedCategory(child)}
                />
              );
            })}
            {shouldAddExtra && <View className="w-[48%] h-1" />}
          </View>
        </View>
      );
    },
    [selectedCategory]
  );

  const onNextStep = useCallback(() => {
    if (!selectedCategory) {
      NativeToast.showToast({
        message: t('pls.select.device.model'),
      });
      return;
    }
    const station: StationDTO | undefined = route.params?.station;

    if (globalMode) {
      navigation.navigate('Scan', {
        station,
        category: selectedCategory,
      });
    } else {
      navigation.navigate('StationSelection', {
        category: selectedCategory,
      });
    }
  }, [navigation, selectedCategory, t]);

  return (
    <View className="flex-1">
      <View
        className="flex-1"
        style={{ backgroundColor: appTheme.colors?.background?.primary }}
      >
        <FlatList
          data={categories}
          renderItem={renderItem}
          keyExtractor={(item, index) => index.toString()}
          windowSize={5}
          maxToRenderPerBatch={10}
          refreshing={loading}
          onRefresh={reloadCategories}
          ListEmptyComponent={ListEmptyLoadingComponent}
          // estimatedItemSize={64}
        />
      </View>
      <SafeAreaView
        edges={['left', 'right', 'bottom']}
        className="px-4 py-3 shadow-sm"
        style={{ backgroundColor: appTheme.colors?.neutral?.white }}
      >
        <Button
          title={t('settings.nextStep')}
          variant="primary"
          onPress={onNextStep}
        ></Button>
      </SafeAreaView>
    </View>
  );
};

export default React.memo(SelectDeviceCategory);

type DeviceItemProps = {
  selectedCategory: DeviceCategoryModel | undefined;
  item: DeviceCategoryModel;
  onPress: () => void;
};

const DeviceItem: React.FC<DeviceItemProps> = React.memo((props) => {
  const isSelected = props.item.id == props.selectedCategory?.id;
  const theme = useAppTheme();
  const backgroundColor = theme.colors?.neutral?.white;
  const resolvedBackgroundColor = isSelected
    ? 'rgba(255, 244, 235, 0.6)'
    : backgroundColor;
  const itemWidth = Math.floor((windowSize.width - 38) / 2);

  return (
    <TouchableOpacity
      className={`flex-row items-center px-3 gap-x-3 rounded-md border-[1px] h-[65px]`}
      style={{
        backgroundColor: resolvedBackgroundColor,
        borderWidth: isSelected ? 1 : 0,
        borderColor: theme.colors?.brand?.primary,
        width: itemWidth,
      }}
      onPress={props.onPress}
    >
      <FastImage
        source={{ uri: StringUtils.toImageUri(props.item.mainImage) }}
        defaultSource={require('@/assets/imgs/MP3000-1.png')}
        className="w-12 h-12"
      />
      <Text className="text-text1">{props.item.name}</Text>
    </TouchableOpacity>
  );
});
